﻿using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RouteConvertTool
{
    public class ExcelParser
    {
        public static List<Waypoint> ParseExcelToWaypoints(string filePath)
        {
            List<Waypoint> waypoints = new List<Waypoint>();

            using (var workbook = new XLWorkbook(filePath))
            {
                var worksheet = workbook.Worksheet(1); // 假设数据在第一个工作表中
             

                int rowCount = worksheet.LastRowUsed().RowNumber();
                for (int currentRow = 2; currentRow <= rowCount; currentRow++) // 从第二行开始读取（假设第一行是标题行）
                {
                    try
                    {
                        // 创建 Waypoint 对象
                        var waypoint = new Waypoint
                        {
                            Coordinates = new Coordinates()
                        };
                        waypoint.No = worksheet.Cell(currentRow, 1).GetValue<int>();

                        // 初始化 Coordinates
                        waypoint.Coordinates.Latitude = worksheet.Cell(currentRow, 14).GetValue<double>();
                        waypoint.Coordinates.Longitude = worksheet.Cell(currentRow, 13).GetValue<double>();
                        waypoint.Coordinates.Altitude = worksheet.Cell(currentRow, 15).GetValue<double>();

                        // 初始化其他属性
                        waypoint.Heading = worksheet.Cell(currentRow, 12).GetValue<double>();
                        waypoint.GimbalPitch = worksheet.Cell(currentRow, 11).GetValue<double>();

                        waypoint.ComponentType = worksheet.Cell(currentRow, 8).GetString();
                        waypoint.ComponentLon = worksheet.Cell(currentRow, 18).GetString();
                        waypoint.ComponentLat = worksheet.Cell(currentRow, 19).GetString();
                        waypoint.ComponentAlt = worksheet.Cell(currentRow, 20).GetString();

                        waypoint.phase = worksheet.Cell(currentRow, 6).GetString();
                        waypoint.routeName = worksheet.Cell(currentRow, 2).GetString();
                        waypoint.towerNo = worksheet.Cell(currentRow, 4).GetString();


                        // 检查是否到达文件末尾
                        if (string.IsNullOrEmpty(waypoint.routeName))
                        {
                            break;
                        }

                        waypoints.Add(waypoint);
                    }
                    catch (Exception ex)
                    {
                        // 如果某一行解析失败，记录错误并跳过该行
                        Console.WriteLine($"Error parsing row {currentRow}: {ex.Message}");
                    }
                }

            }

            return waypoints;
        }
    }
}
